package br.com.advance.automacao.web.example;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import br.com.advance.automacao.web.utils.BaseBean;

@ManagedBean
@SessionScoped
public class PrincipalMBean extends BaseBean {

	private static final long serialVersionUID = 5245699923284307519L;
	private static final Logger logger = Logger.getLogger(PrincipalMBean.class);

	private String usuario;
	private String senha;

	private String usuarioEsperado = "advance";
	private String senhaEsperada = "33f408a29b08904cdcb1cf8ec23a0177";

	public void initialize() {
		logger.info("PrincipalMBean.initialize()");
	}

	public void login() {
		try {

			if (efetuarLogin()) {
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Login realizado com sucesso.", null));
				FacesContext.getCurrentInstance().getExternalContext().redirect("/advance/index.jsf");
			} else {
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Usuário ou senha inválido(s).", null));
			}
		} catch (IOException e) {
			logger.error("Erro ao fazer redirect", e);
		} catch (NoSuchAlgorithmException e) {
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro ao efetuar login.", null));
			logger.error("Erro ao gerar senha em MD5", e);
		}
	}

	public void logout() {
		try {
			FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("logado", false);
			HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
			request.getSession().invalidate();
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Logout realizado com sucesso.", null));
			FacesContext.getCurrentInstance().getExternalContext().redirect("/advance/index.jsf");
		} catch (IOException e) {
			logger.error("Erro ao fazer redirect", e);
		}
	}

	private boolean efetuarLogin() throws NoSuchAlgorithmException {
		if (this.usuarioEsperado.equals(usuario) && this.senhaEsperada.equals(obterSenhaEmMD5(senha))) {
			FacesContext.getCurrentInstance().getExternalContext().getSession(true);
			FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("logado", true);
			return true;
		}
		return false;
	}

	private static String obterSenhaEmMD5(String senha) throws NoSuchAlgorithmException {
		MessageDigest m = MessageDigest.getInstance("MD5");
		m.update(senha.getBytes());
		byte[] mdBytes = m.digest();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < mdBytes.length; i++) {
			sb.append(Integer.toString((mdBytes[i] & 0xff) + 0x100, 16).substring(1));
		}
		return sb.toString();
	}

	public String getUsuario() {
		return usuario;
	}

	public void setUsuario(String usuario) {
		this.usuario = usuario;
	}

	public String getSenha() {
		return senha;
	}

	public void setSenha(String senha) {
		this.senha = senha;
	}
}
